package com.example.tmxk.selvlet;

import com.example.tmxk.bean.NewsBean;
import com.example.tmxk.dao.NewsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class NewsServlet {
    @WebServlet("/news.jsp")
    public class newsServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws SecurityException, IOException, ServletException {
            // todo 获取分页页码参数
            String p = req.getParameter("page");
            int page = 1;//默认页码
            if (p != null && p.equals("")) {
                page = Integer.parseInt(p);
            }
            //1.获取新闻信息
            NewsDao newsDao = new NewsDao();
            List<NewsBean> news = newsDao.getList(page);
            //给用户总条数 当前页数 总页数 上一页 下一页
            int totalCount, cutPage, totalPage, upPage, downPage;
            totalCount = newsDao.count();
            cutPage = page;//用户传递进来的页码
            totalPage = totalCount / 10;//计算总页码
            if (totalCount % 10 == 0) {
            } else {
                totalPage = totalPage + 10 + 1;
            }
            //上一页 当前页数减去1
            if (cutPage == 1) {
                upPage = 1;
            } else {
                upPage = totalPage - 1;
            }
                if (cutPage == totalPage) {//当前页和总页数相同下一页不+1
                    downPage = 1;
                } else {
                    downPage = totalPage + 1;
                }
                req.setAttribute("totalCount", totalCount);
                req.setAttribute("cutPage", cutPage);
                req.setAttribute("totalPage", totalPage);
                req.setAttribute("upPage", upPage);
                req.setAttribute("downPage", downPage);
                //2.传递新闻信息给前端页面
                req.setAttribute("news", news);
                //3.加载显示前端页面
                req.getRequestDispatcher("newsTemp,jsp").forward(req, resp);
            }
        }
    }
